﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Xml.Linq;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace kiosk
{
    public partial class SettingsForm : Form
    {

        private bool nonNumberEntered;
        private DataBaseHandler handler;
        private Boolean force;
        private bool TxtChanged = false;
       // private String rootUname;
        //private String rootPass;
       
        //
        String svrAddress ;
        String svrDatabaseName; 
        int svrPortNo ;
        String svrUsrName; 
        String pass;
            
        //


        private const int CP_NOCLOSE_BUTTON = 0x200;



        public SettingsForm(bool force)
        {
            InitializeComponent();

            this.svrPassword2.KeyPress += new KeyPressEventHandler(svrPassword2_KeyPress);
            this.svrAddTxt.KeyPress += new KeyPressEventHandler(svrAddTxt_KeyPress);
            this.svrDatabase.KeyPress += new KeyPressEventHandler(svrDatabase_KeyPress);
            this.svrPassword.KeyPress += new KeyPressEventHandler(svrPassword_KeyPress);
            this.SvrPort.KeyPress += new KeyPressEventHandler(SvrPort_KeyPress);
            this.svrUName.KeyPress += new KeyPressEventHandler(svrUName_KeyPress);
            this.svrAddTxt.TextChanged += new EventHandler(TxtData_TextChanged);
            this.svrDatabase.TextChanged += new EventHandler(TxtData_TextChanged);
            this.svrPassword.TextChanged += new EventHandler(TxtData_TextChanged);
            this.svrPassword2.TextChanged += new EventHandler(TxtData_TextChanged);
            this.svrUName.TextChanged += new EventHandler(TxtData_TextChanged);
            this.SvrPort.TextChanged += new EventHandler(TxtData_TextChanged);
            this.force = force;



        }



        #region eventhandlers

        void svrUName_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (Char)13)
                this.svrPassword.Focus();
        }

        void svrPassword_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (Char)13)
                this.svrPassword2.Focus();
        }

        void svrDatabase_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (Char)13)
                this.SvrPort.Focus();
        }

        void svrAddTxt_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (Char)13)
                this.svrDatabase.Focus();
        }

        void svrPassword2_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (Char)13)
                this.settSaveBtn.Focus();


        }

        protected override CreateParams CreateParams
        {
            get
            {
                if (force)
                {

                    CreateParams myCp = base.CreateParams;
                    myCp.ClassStyle = myCp.ClassStyle | CP_NOCLOSE_BUTTON;
                    return myCp;
                }
                else
                {
                    return base.CreateParams;

                }
            }
        }

        void TxtData_TextChanged(object sender, EventArgs e)
        {

            this.TxtChanged = true;


        }


        #endregion




        // setting that saves the configeration in the registryty

        private void settSaveBtn_Click(object sender, EventArgs e)
        {
            // first check to see if there is empty fields 


            if (this.svrAddTxt.Text.Trim() == String.Empty)
            {
                MessageBox.Show("Server Address cannot be empty !!");
                return;

            }


            if (this.svrUName.Text.Trim() == String.Empty)
            {
                MessageBox.Show("Server UserName Can not be Empty !!");
                return;

            }

            if (this.svrDatabase.Text.Trim() == String.Empty && this.settSaveBtn.Text != "Ok")
            {

                MessageBox.Show(" Database name cannot be Empty ");
                return;

            }


            if (this.svrPassword.Text.Trim() == String.Empty || this.svrPassword2.Text.Trim() == String.Empty || this.svrPassword.Text.Trim() != this.svrPassword2.Text.Trim())
            {
                MessageBox.Show("The Server Password Fild is empty or the Typed Password Does not match !! Please check the U have given the Password ");
                return;


            }
            if (this.aniChoCbo.SelectedItem == null)
            {
                MessageBox.Show("Select an value form the Combo");
                return;
            
            }

            // modified
            if (!this.useExisRtn.Checked && !this.NuExRbtn.Checked )
            {
                MessageBox.Show("Please select an DataBase creation option (_ Use Existing Account or not ) ");
                return;
            
            }


            // Check is the Server Config is correct (We can connect to the database)

             svrAddress = this.svrAddTxt.Text.Trim();
             svrDatabaseName = this.svrDatabase.Text.Trim();
             svrPortNo = Convert.ToInt32(this.SvrPort.Text);
             svrUsrName = this.svrUName.Text.Trim();
             pass = this.svrPassword.Text.Trim();
             int index = this.aniChoCbo.SelectedIndex;
            
            if(handler == null)
               handler = new DataBaseHandler();



                MySQLMessage msg = handler.checkConfig(svrAddress, svrUsrName, svrDatabaseName, svrPortNo, pass);

                ///  check the message from the mysql server

                if (msg != MySQLMessage.Success)
                {
                    if (msg == MySQLMessage.HostError)
                    {
                        MessageBox.Show(" Fatal Error !! cannot able to find a sutiable MySQL server !!! \r\n Please check the server address gven and the Port Address !!");
                        return;

                    }

                    else if (msg == MySQLMessage.AuthencationError && index == 0)
                    {
                        // Authencation error occued 
                        MessageBox.Show("The following user" + this.svrUName.Text + " With the password : XXXXXX  Does not exists \r\n Do you want to create a new user with the specified configeration ?? \r\n If not Please check the user Name And the Password to see if you made any mistake !! ", "Question ", MessageBoxButtons.OK);

                        
                            
                            
                            
                            
                            
                            //// the user wants to create a new User In specified name 
                            //MessageBox.Show("Please provide root password and Username !!");
                            //this.settSaveBtn.Enabled = false;
                            //this.settSaveBtn.Visible = false;

                            //this.exitButtn.Enabled = false;
                            //this.svrDatabase.Enabled = false;
                            //this.svrUName.Text = String.Empty;
                            //this.svrPassword.Text = String.Empty;
                            //this.svrPassword2.Text = String.Empty;
                            //this.svrAddTxt.Enabled = false;
                            //this.SvrPort.Enabled = false;
                            //this.rootBtn.Enabled = true;
                            //this.rootBtn.Visible = true;
                            return;

                        




                    }

                    else if (msg == MySQLMessage.UnknownDataBase && index == 0 )
                    {
                        ///
                        /// Currently not implemented because of MySQL BACKUP Failure

                        // Create the database in the server
                        //this.handler.createDataBase(this.svrAddress, this.svrPortNo, this.svrUsrName, this.pass, this.svrDatabaseName);
                       
                        //this.saveXMLSetting(this.svrAddress, this.svrPortNo, this.svrDatabaseName, this.svrUsrName, this.pass);
                        //MessageBox.Show("Settings Sucessfully saved in : \r\n ");
                        //this.TxtChanged = false;
                        MessageBox.Show("UnKnown DataBase Error");
                        return;
                    
                    }
                    
                   

               }



                this.saveXMLSetting(this.svrAddress, this.svrPortNo, this.svrDatabaseName, this.svrUsrName, this.pass);

                MessageBox.Show("Settings Saved  !!");
                this.TxtChanged = false;

            //
            //MessageBox.Show("Settings Sucessfully saved in : \r\n ");
            //this.saveXMLSetting(this.svrAddress, this.svrPortNo, this.svrDatabaseName, this.svrUsrName, this.pass);
            //


        }




        // Saves the xml file saving
        private void saveXMLSetting(string svrAddress, int svrPortNo, string svrDatabaseName, string svrUsrName, string userPassword)
        {


            // the Setting is ok So save the Data in the Xml file

            /// The Xml scama is shown below 
            /// check if the file exists
            /// 

            String settingFpath = System.IO.Path.Combine(Application.StartupPath, GeneralOpt.AppSettingsFileName);

            if (!System.IO.File.Exists(settingFpath))
            {
                // create a new Xml File 
                XElement AppSetting = new XElement("ApplicationSettings",
                         new XElement("Server",
                             new XElement("SvrAddress", svrAddress, new XAttribute("SvrPort", svrPortNo.ToString()))),
                             new XElement("Database",
                               new XElement("Name", svrDatabaseName, new XAttribute("UserName", svrUsrName), new XAttribute("UserPassword", pass))),
                               new XElement("Animation", this.aniChoCbo.SelectedItem.ToString()));



                AppSetting.Save(settingFpath);




            }
            else
            {
                // file exists so update the file
                XDocument document = XDocument.Load(settingFpath);
                // iterate thriough eachof the element and save the settings
                XElement root = document.Root;
                if (root.IsEmpty)
                {
                    // create all the xhild elements of the nodes

                    root.Add(
                         new XElement("Server",
                             new XElement("SvrAddress", svrAddress, new XAttribute("SvrPort", svrPortNo.ToString()))),
                             new XElement("Database",
                               new XElement("Name", svrDatabaseName, new XAttribute("UserName", svrUsrName), new XAttribute("UserPassword", pass))),
                                new XElement("Animation", this.aniChoCbo.SelectedItem.ToString()));


                }
                else
                {

                    if (root.Element("Server") == null)
                    {

                        root.Add(new XElement("Server",
                                 new XElement("SvrAddress", svrAddress, new XAttribute("SvrPort", svrPortNo.ToString()))));
                    }
                    else
                    {
                        if (root.Element("Server").IsEmpty)
                        {
                            root.Element("Server").Remove();
                            root.Add(new XElement("Server",
                                 new XElement("SvrAddress", svrAddress, new XAttribute("SvrPort", svrPortNo.ToString()))));


                        }


                        else if (root.Element("Server").Element("SvrAddress") == null)
                        {

                            root.Element("Server").Add(
                                   new XElement("SvrAddress", svrAddress, new XAttribute("SvrPort", svrPortNo.ToString())));

                        }

                        else if (root.Element("Server").Element("SvrAddress").IsEmpty)
                        {

                            root.Element("Server").Element("SvrAddress").Remove();
                            root.Element("Server").Add(
                                 new XElement("SvrAddress", svrAddress, new XAttribute("SvrPort", svrPortNo.ToString())));


                        }
                        else
                        {

                            //Update it
                            root.Element("Server").SetElementValue("SvrAddress", svrAddTxt);
                            root.Element("Server").Element("SvrAddress").SetAttributeValue("svrPort", svrPortNo.ToString());



                        }



                    }




                    if (root.Element("Database") == null)
                    {

                        root.Add(new XElement("Database",
                                new XElement("Name", svrDatabaseName, new XAttribute("UserName", svrUsrName), new XAttribute("UserPassword", pass))));


                    }
                    else
                    {
                        if (root.Element("Database").Element("Name") == null)
                            root.Element("Database").Add(new XElement("Name", svrDatabaseName, new XAttribute("UserName", svrUsrName), new XAttribute("UserPassword", pass)));

                        else if (root.Element("Database").Element("Name").IsEmpty)
                        {
                            root.Element("Database").Element("Name").Remove();
                            root.Element("Database").Add(new XElement("Name", svrDatabaseName, new XAttribute("UserName", svrUsrName), new XAttribute("UserPassword", pass)));

                        }
                        else
                        {
                            // update
                            root.Element("Database").SetElementValue("Name", svrDatabaseName);
                            root.Element("Database").Element("Name").SetAttributeValue("UserName", svrUsrName);
                            root.Element("Database").Element("Name").SetAttributeValue("UserPassword", pass);


                        }




                    }


                    if (root.Element("Animation") == null)
                    {



                        root.Add(new XElement("Animation", this.aniChoCbo.SelectedItem.ToString()));



                    }
                    else
                    {

                        if (root.Element("Animation").IsEmpty)
                        {
                            root.Element("Animation").Remove();
                            root.Add(new XElement("Animation", this.aniChoCbo.SelectedItem.ToString()));


                        }
                        else
                        {
                            root.Element("Animation").SetValue(this.aniChoCbo.SelectedItem.ToString());

                        }

                    }

                    // all the elements exists so update the xml file



                }

                document.Save(settingFpath);

            }
        }

            //
               
        








        // 
        private void SvrPort_KeyDown(object sender, KeyEventArgs e)
        {

            // Initialize the flag to false.
            nonNumberEntered = false;

            // Determine whether the keystroke is a number from the top of the keyboard.
            if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
            {
                // Determine whether the keystroke is a number from the keypad.
                if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
                {
                    // Determine whether the keystroke is a backspace.
                    if (e.KeyCode != Keys.Back)
                    {
                        // A non-numerical keystroke was pressed.
                        // Set the flag to true and evaluate in KeyPress event.
                        nonNumberEntered = true;
                    }
                }
            }
            //If shift key was pressed, it's not a number.
            if (Control.ModifierKeys == Keys.Shift)
            {
                nonNumberEntered = true;
            }


        }

        private void SvrPort_KeyPress(object sender, KeyPressEventArgs e)
        {


            if (e.KeyChar == (Char)13)
                this.svrPassword.Focus();


            // Check for the flag being set in the KeyDown event.
            if (nonNumberEntered == true)
            {
                // Stop the character from being entered into the control since it is non-numerical.
                e.Handled = true;
            }


        }

        private void SettingsForm_Load(object sender, EventArgs e)
        {

            // Load the settings file if they exists
            String settingFpath = System.IO.Path.Combine(Application.StartupPath, GeneralOpt.AppSettingsFileName);
            if (File.Exists(settingFpath))
            {

                // XElement docu = XElement.Load(settingFpath);
                XDocument docu = XDocument.Load(settingFpath);
                if (docu.Root != null)
                {
                    XElement server = docu.Root.Element("Server");
                    if (server != null)
                    {

                        server = server.Element("SvrAddress");
                        if (server != null)
                        {
                            this.svrAddTxt.Text = server.Value;
                            this.SvrPort.Text = server.Attribute("SvrPort").Value;

                        }
                    }

                    XElement Database = docu.Root.Element("Database");

                    if (Database != null)
                    {

                        Database = Database.Element("Name");



                        if (Database != null)
                        {
                            this.svrDatabase.Text = Database.Value;
                            this.svrUName.Text = Database.Attribute("UserName").Value;
                            this.svrPassword.Text = Database.Attribute("UserPassword").Value;
                            this.svrPassword2.Text = Database.Attribute("UserPassword").Value;
                        }
                    }






                    if (docu.Element("Animation") == null)
                    {
                        this.aniChoCbo.SelectedItem = 0;
                    }
                    else
                    { 
                        string val = docu.Element("Animation").Value;
                        if(val == "Yes")
                            this.aniChoCbo.SelectedIndex = 0;
                        else
                            this.aniChoCbo.SelectedIndex = 1;

                       
                    }
                }

            }
            this.useExisRtn.Checked = true;

            this.NuExRbtn.Enabled = false;

        }

        private void exitButtn_Click(object sender, EventArgs e)
        {

            if (this.TxtChanged)
            {
                MessageBox.Show("You have not saved your Changes Please save the Changes ...");
                return;

            }

            this.Close();

        }

      
      
    }
}
